package edu.uoc.tds.pac4.DAO;

import java.util.Enumeration;
import java.util.Hashtable;

/***
 * Classe per a montar Sentencies SQL (INSERT, UPDATE)
 */
public class InsertUpdate extends Sentencia {
	private Hashtable<String,String> contingut;
	
	public InsertUpdate(String from, String where) {
		super(from, where);
		this.contingut = new Hashtable<String,String>();
	}

	/***
	 * Afegir contingut String a la sentencia	
	 * @param camp
	 * @param valor
	 */
	public void addContingut(String camp, String valor){
		if(valor!=null)
			this.contingut.put(camp, valor);
		else
			this.contingut.put(camp, "null");
	}

	/***
	 * Obtenir String amb tots els camps	
	 * @return
	 */
	private String getCamps(){
		StringBuffer sb = new StringBuffer();
		Enumeration<String> e = this.contingut.keys();
		
		while(e.hasMoreElements()){
			sb.append(e.nextElement());
			if(e.hasMoreElements())
				sb.append(",");
			sb.append(" ");
		}
		
		return sb.toString();
	}
	/***
	 * Obtenir String amb tots els valors
	 * @return
	 */
	private String getValors(){
		StringBuffer sb = new StringBuffer();
		Enumeration<String> e = this.contingut.keys();
		
		while(e.hasMoreElements()){
			sb.append(this.contingut.get(e.nextElement()));
			if(e.hasMoreElements())
				sb.append(",");
			sb.append(" ");
		}
		
		return sb.toString();
	}

	/***
	 * Obtenir un String per al SET del Update
	 * @return
	 */
	private String getContingut(){
		StringBuffer sb = new StringBuffer();
		String camp;
		Enumeration<String> e = this.contingut.keys();
		
		while(e.hasMoreElements()){
			camp=e.nextElement();
			sb.append(camp).append("=").append(this.contingut.get(camp));
			if(e.hasMoreElements())
				sb.append(",");
			sb.append(" ");
		}
		
		return sb.toString();
	}

	/***
	 *  Monta la sentencia, si te where monta un UPDATE si no te monta un INSERT
	 */
	public String toString(){
		StringBuffer sb = new StringBuffer();
		
		if(this.getWhere()=="")//es insert
		{
			sb.append(" INSERT INTO ").append(this.getTableName())
			.append(" (").append(this.getCamps())
			.append(") VALUES (").append(this.getValors()).append(")");
		}else //es update
		{
			sb.append(" UPDATE ").append(this.getTableName())
			.append(" SET ").append(this.getContingut())
			.append(this.getWhere());
		}

		return sb.toString();
	}
}
